﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IO;
using System.Text;
using LeoGemini.Service.Infrastructure.Security.Authentication.JwtBearer;

namespace LeoGemini.Service.Infrastructure.Extension
{
    public partial class Extensions
    {
        public static AuthenticationBuilder AddOcelotJwtAuthorize(
            this IServiceCollection services)
        {
            // 获取配置
            var configuration = BuildConfiguration();
            IConfigurationSection config = configuration.GetSection("JwtAuthorize");

            if (configuration == null)
                throw new Exception("IConfiguration没有被注入");

            return services
                .AddAuthentication(options => options.DefaultScheme = config["DefaultScheme"])
                .AddJwtBearer(config["DefaultScheme"], opt =>
                {
                    opt.RequireHttpsMetadata = bool.Parse(config["IsHttps"]);
                    opt.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config["Secret"])),
                        ValidateIssuer = true,
                        ValidIssuer = config["Issuer"],
                        ValidateAudience = true,
                        ValidAudience = config["Audience"],
                        ValidateLifetime = true,
                        RequireExpirationTime = bool.Parse(config["RequireExpirationTime"])
                    };
                });
        }

        public static IServiceCollection AddTokenJwtAuthorize(
            this IServiceCollection services)
        {
            // 获取配置
            var configuration = BuildConfiguration();

            IConfigurationSection config = configuration.GetSection("JwtAuthorize");
            
            return services.AddSingleton(p =>
                new JwtAuthorizationRequirement
                {
                    Issuer = config["Issuer"],
                    Audience = config["Audience"],
                    SigningCredentials = new SigningCredentials(
                        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Secret"])), "HS256")
                });
        }
        
        public static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);
            return builder.Build();
        }
    }
}